import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/api'

export const useUserStore = defineStore('user', () => {
  // 用户信息
  const userInfo = ref(null)
  // token
  const token = ref(uni.getStorageSync('token') || '')
  
  // 登录
  const login = async (params) => {
    try {
      const res = await api.user.login(params)
      if (res.code === 0) {
        token.value = res.data.token
        userInfo.value = res.data.userInfo
        // 存储token
        uni.setStorageSync('token', res.data.token)
      }
      return res
    } catch (error) {
      return Promise.reject(error)
    }
  }
  
  // 登出
  const logout = () => {
    token.value = ''
    userInfo.value = null
    uni.removeStorageSync('token')
  }
  
  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const res = await api.user.getUserInfo()
      if (res.code === 0) {
        userInfo.value = res.data
      }
      return res
    } catch (error) {
      return Promise.reject(error)
    }
  }
  
  // 添加微信手机号登录方法
  const wxPhoneLogin = async (params) => {
    try {
      const res = await api.user.wxPhoneLogin(params)
      if (res.code === 0) {
        token.value = res.data.token
        userInfo.value = res.data.userInfo
        uni.setStorageSync('token', res.data.token)
      }
      return res
    } catch (error) {
      return Promise.reject(error)
    }
  }
  
  return {
    userInfo,
    token,
    login,
    logout,
    getUserInfo,
    wxPhoneLogin  // 导出新方法
  }
}) 